package com.wondertek.poms.pre.manager.filter;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.XmlUtil;
import com.wondertek.poms.common.constant.Constants;
import com.wondertek.poms.transform.xmlvo.MyResponse;
import com.wondertek.poms.transform.xmlvo.SvcCont;
import com.wondertek.poms.transform.xmlvo.SyncResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author evan0213
 * @description 上游数据合法性校验
 */
@Component
@Slf4j
public class MainProcessPreFilter {
	@Value(value = "${syncpre.mam.path}")
	public String mamPath;

	public SyncResponse filterData(Document doc, SvcCont svcCont) {
		String formType = getXmlValueByKey(doc, Constants.FORM_TYPE);
		if (StringUtils.isBlank(formType)) {
			log.info("FormType is null:" + svcCont.getContentID());
			return backResponse(SyncResponse.back_error_500105, "FormType not exists");
		}
		String type = getXmlValueByKey(doc, Constants.PRD_TYPE);
		if (StringUtils.isBlank(type)) {
			log.info("Type is null:" + svcCont.getContentID());
			return backResponse(SyncResponse.back_error_500110, "Type not exists");
		}
		//直播频道父id不为空
		if (formType.equals(Constants.ASSET_FORM_TYPE_8) && StringUtils.isNotBlank(type) &&
				(type.equals(Constants.PRD_CONT_TYPE_8)
						|| type.equals(Constants.PRD_CONT_TYPE_9)
						|| type.equals(Constants.PRD_CONT_TYPE_12))) {
			String liveContentID = getXmlValueByKey(doc, Constants.LIVE_CONTENT_ID);
			if (StringUtils.isNotBlank(liveContentID)) {
				log.info("LiveContentID is not null:" + svcCont.getContentID());
				return backResponse(SyncResponse.back_error_500109, "LiveContentID exists");
			}
		}
		//直播节目父id为空
		if (formType.equals(Constants.ASSET_FORM_TYPE_13)) {
			String liveContentID = getXmlValueByKey(doc, Constants.LIVE_CONTENT_ID);
			if (StringUtils.isBlank(liveContentID)) {
				log.info("LiveContentID is null:" + svcCont.getContentID());
				return backResponse(SyncResponse.back_error_500108, "LiveContentID not exists");
			}
		}
		//壳节目父id不为空
		if (formType.equals(Constants.ASSET_FORM_TYPE_6)) {
			String serialContentID = getXmlValueByKey(doc, Constants.SERIAL_CONTENT_ID);
			if (StringUtils.isNotBlank(serialContentID)) {
				log.info("SerialContentID is not null:" + svcCont.getContentID());
				return backResponse(SyncResponse.back_error_500107, "SerialContentID exists");
			}
			String serialCount = getXmlValueByKey(doc, Constants.SERIAL_COUNT);
			if (StringUtils.isBlank(serialCount)) {
				log.info("SerialCount is null:" + svcCont.getContentID());
				return backResponse(SyncResponse.back_error_500112, "SerialCount not exists");
			}
		}
		//子集父id为空
		if (formType.equals(Constants.ASSET_FORM_TYPE_7)) {
			String serialContentID = getXmlValueByKey(doc, Constants.SERIAL_CONTENT_ID);
			if (StringUtils.isBlank(serialContentID)) {
				log.info("SerialContentID is null:" + svcCont.getContentID());
				return backResponse(SyncResponse.back_error_500106, "SerialContentID not exists");
			}
			String serialSequence = getXmlValueByKey(doc, Constants.SERIAL_SEQUENCE);
			if (StringUtils.isBlank(serialSequence)) {
				log.info("SerialSequence is null:" + svcCont.getContentID());
				return backResponse(SyncResponse.back_error_500111, "SerialSequence not exists");
			}
		}
		//关键列为空
		String contentId = getXmlValueByKey(doc, Constants.CONTENT_ID);
		if (StringUtils.isBlank(contentId)) {
			log.info("contentId is null:" + svcCont.getContentID());
			return backResponse(SyncResponse.back_error_500113, "contentId not exists");
		}
		String name = getXmlValueByKey(doc, Constants.NAME);
		if (StringUtils.isBlank(name)) {
			log.info("Name is null:" + svcCont.getContentID());
			return backResponse(SyncResponse.back_error_500114, "Name not exists");
		}
		String copyrightObjectId = getXmlValueByKey(doc, Constants.COPYRIGHT + "/" + Constants.COPYRIGHT_OBJECT_ID);
		if (StringUtils.isBlank(copyrightObjectId)) {
			log.info("CopyRightObjectID is null:" + svcCont.getContentID());
			return backResponse(SyncResponse.back_error_500115, "CopyRightObjectID not exists");
		}
		String cDuration = getXmlValueByKey(doc, Constants.CDuration);
		if (StringUtils.isBlank(cDuration)) {
			log.info("CDuration is null:" + svcCont.getContentID());
			return backResponse(SyncResponse.back_error_500116, "CDuration not exists");
		}
		if (!NumberUtil.isNumber(cDuration)) {
			log.info("CDuration is not a number:" + svcCont.getContentID());
			return backResponse(SyncResponse.back_error_500117, "CDuration not a number");
		}
		String displayType = getXmlValueByKey(doc, Constants.DISPLAY_TYPE);
		if (StringUtils.isBlank(displayType)) {
			log.info("DisplayType is null:" + svcCont.getContentID());
			return backResponse(SyncResponse.back_error_500118, "DisplayType not exists");
		}
		return null;
	}

	public SyncResponse filterSrcImages(SvcCont svcCont) {
		String mamXml = mamPath + svcCont.getBasePath() + File.separator +
				svcCont.getContentID() + File.separator + Constants.syncFile_baseName;
		log.info("同步流程|媒资xml路径:" + mamXml);
		File file = new File(mamXml);
		List<String> nameList = new ArrayList<>();
		SAXReader saxReader = new SAXReader();
		org.dom4j.Document doc = null;
		try {
			doc = saxReader.read(file);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		Element root = doc.getRootElement();
		Element element = root.element("DisPlayFileLists");
		Iterator iterator = element.elementIterator("DisPlayFile");
		while (iterator.hasNext()) {
			Element next = (Element) iterator.next();
			nameList.add(next.element("DpFileName").getStringValue());
		}
		if (nameList.size() == 0) {
			log.info("sc image is null:" + svcCont.getContentID());
			return backResponse(SyncResponse.back_error_500119, "sc image not exists");
		}
		for (String name : nameList) {
			if (!name.contains("sc")) {
				log.info("sc image name is illegal:" + svcCont.getContentID());
				return backResponse(SyncResponse.back_error_500120, "sc image is name illegal");
			}
		}
		return null;
	}

	/**
	 * <p><b>Title:</b> getAssetID</p>
	 * <p><b>Description:</b> 获取媒资id</p>
	 *
	 * @param svcCont
	 * @param key
	 * @return
	 * @throws IOException
	 * @author douzi
	 */
	public String getXmlValueByKey(Document doc, String key) {
		Node assetIdNode = XmlUtil.getNodeByXPath("/Content/" + key + "/node()", doc);
		if (assetIdNode == null) {
			log.info("{}在xml文件中没有值", key);
			return null;
		}
		return assetIdNode.getNodeValue();
	}

	/**
	 * <p><b>Title:</b> backResponse </p>
	 * <p><b>Description:</b> 返回xml结构数据给mcms</p>
	 *
	 * @param result
	 * @param message
	 * @return
	 * @author douzi
	 */
	public SyncResponse backResponse(String result, String message) {
		MyResponse response = MyResponse.builder()
				.rspCode(result)
				.rspDesc(result)
				.build();
		return SyncResponse.builder().response(response).build();
	}

	public Document getDocument(SvcCont svcCont) {
		String mamXml = mamPath + svcCont.getBasePath() + File.separator +
				svcCont.getContentID() + File.separator + Constants.syncFile_baseName;
		log.info("同步流程|媒资xml路径:" + mamXml);
		File file = new File(mamXml);
		if (!file.exists()) {
			log.error("内容：" + svcCont.getContentID() + "|Metadata_M.xml not exists");
			return null;
		}
		return XmlUtil.readXML(file);
	}
}
